package com.qzsoft.zhjd.collect.modules.product.service.impl;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qzsoft.system.common.ConvertUtils;
import com.qzsoft.zhjd.collect.modules.dosage.dto.CollectDosageDto;
import com.qzsoft.zhjd.collect.modules.dosage.entity.CollectDosageEntity;
import com.qzsoft.zhjd.collect.modules.dosage.mapper.CollectDosageMapper;
import com.qzsoft.zhjd.collect.modules.piece.dto.CollectPieceDto;
import com.qzsoft.zhjd.collect.modules.piece.entity.CollectPieceEntity;
import com.qzsoft.zhjd.collect.modules.piece.mapper.CollectPieceMapper;
import com.qzsoft.zhjd.collect.modules.product.dto.CollectProductDto;
import com.qzsoft.zhjd.collect.modules.product.dto.StatisticsProductDto;
import com.qzsoft.zhjd.collect.modules.product.entity.CollectProductEntity;
import com.qzsoft.zhjd.collect.modules.product.mapper.CollectProductMapper;
import com.qzsoft.zhjd.collect.modules.product.model.xm.*;
import com.qzsoft.zhjd.collect.modules.product.service.CollectProductService;
import com.qzsoft.zhjd.common.components.BaseServiceComponent;
import com.qzsoft.zhjd.common.utils.DateUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * 派车信息
 */
@Service
public class CollectProductServiceImpl extends ServiceImpl<CollectProductMapper, CollectProductEntity> implements CollectProductService {

    @Autowired
    private BaseServiceComponent baseServiceComponent;
    @Autowired
    private CollectPieceMapper collectPieceMapper;
    @Autowired
    private CollectDosageMapper collectDosageMapper;

    @Override
    public IPage<CollectProductDto> page(Map<String, Object> params) {
        IPage<CollectProductDto> page = baseServiceComponent.getPage(params, CollectProductDto.class);
        return baseMapper.query(page, params);
    }

    @Override
    public void saveCollectData(CollectProductDto dto) {
        CollectProductEntity productEntity = ConvertUtils.sourceToTarget(dto, CollectProductEntity.class);
        //文双二分部疾控中心数据剔除
        if("WD2FBHNT01".equals(dto.getStationCode())&& dto.getConsPos().contains("疾控中心")){
            return;
        }
        baseMapper.insert(productEntity);

        for (CollectPieceDto piece : dto.getPieceList()) {
            CollectPieceEntity pieceEntity = ConvertUtils.sourceToTarget(piece, CollectPieceEntity.class);
            pieceEntity.setParentPkId(productEntity.getPkId());
            collectPieceMapper.insert(pieceEntity);

            for (CollectDosageDto dosage : piece.getDosageList()) {
                CollectDosageEntity dosageEntity = ConvertUtils.sourceToTarget(dosage, CollectDosageEntity.class);
                dosageEntity.setParentPkId(pieceEntity.getPkId());
                collectDosageMapper.insert(dosageEntity);
            }

        }
        try{
            productPkIdSend(productEntity.getPkId());
        } catch (Exception e){
            e.printStackTrace();
        }

    }


    /**
     * 保存欣盟混凝土拌和站数据（需要将欣盟的数据结构变成博硕的数据结构进行存储）
     */
    @Override
    public void saveXmCollectData(TaskVehicleModel taskVehicle) {
        CollectProductEntity productEntity = ConvertUtils.sourceToTarget(taskVehicle, CollectProductEntity.class);
        productEntity.setId(taskVehicle.getId().intValue());
        //生产盘数
        productEntity.setPieCnt(taskVehicle.getPieceList().size());
        //累计车次/生产时，任务单累计送货车次
        productEntity.setTotVehs(taskVehicle.getRwcc().intValue());
        //累计方量/生产时，任务单累计生产方量
        productEntity.setTotMete(BigDecimal.valueOf(taskVehicle.getRwfl()).setScale(1, RoundingMode.HALF_UP).doubleValue());
        //生产任务
        TaskModel task = taskVehicle.getTask();
        if (task != null) {
            //任务单编号
            productEntity.setCode(task.getCode());
            //合同信息/合同编号
            productEntity.setContract(task.getContract());
            //客户名称/委托单位
            productEntity.setCustomer(task.getCustomer());
            //工程名称
            productEntity.setProjName(task.getProjName());
            //工程类别
            productEntity.setProjType(task.getProjType());
            //工程级别/工程等级
            productEntity.setProjGrade(task.getProjGrade());
            //开工面积
            productEntity.setProjArea(task.getProjArea());
            //施工地址/工程地址
            productEntity.setProjAdr(task.getProjAdr());
            //运输距离
            productEntity.setDistance(task.getDistance());
            //施工部位
            productEntity.setConsPos(task.getConsPos());
            //浇筑方式/浇筑方法
            productEntity.setPour(task.getPour());
            //任务方量/计划用量
            productEntity.setMete(task.getMete());
            //任务调度/下达任务人姓名
            productEntity.setAttamper(task.getAttamper());
            //质检员/技术负责人姓名
            productEntity.setQualitor(task.getQualitor());

        }
        //生产纪录盘次
        List<PieceModel> pieceList = taskVehicle.getPieceList();
        if (!pieceList.isEmpty()) {
            //生产配比
            RatioModel ratio = pieceList.get(0).getRatio();
            //为了符合博硕数据结构，需要从配比中提取一些数据
            if (ratio != null) {
                //强度等级
                productEntity.setBetLev(ratio.getQddj());
                //抗渗等级
                productEntity.setFilter(ratio.getKsdj());
                //抗冻等级
                productEntity.setFreeze(ratio.getKddj());
                //坍落度
                productEntity.setLands(ratio.getTld());
                //水泥品种/水泥标号
                productEntity.setCement(ratio.getCement());
                //石子种类
                productEntity.setStone(ratio.getStone());
                //骨料粒径
                productEntity.setBonSize(ratio.getBonsiz());
                //外加剂要求/外加剂种类
                productEntity.setAddLiq(ratio.getAppliq());
                //外加剂要求/配合比编号
                productEntity.setRecipe(ratio.getPbbh());
            }
        }
        baseMapper.insert(productEntity);
        //盘次
        for (PieceModel piece : pieceList) {
            CollectPieceEntity pieceEntity = new CollectPieceEntity();
            pieceEntity.setParentPkId(productEntity.getPkId());
            pieceEntity.setId(piece.getId().intValue());
            //生产时刻/投料开始时间
            pieceEntity.setDatTim(piece.getDts());
            //搅拌机/生产机号
            pieceEntity.setBlend(taskVehicle.getMachineNumber());
            pieceEntity.setSerial(piece.getPc().intValue());
            //搅拌时间/投料开始时间
            pieceEntity.setBldTim(DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", piece.getDts()));
            //盘方量/本盘方量
            pieceEntity.setPieAmnt(piece.getFl());
            //本盘坍落度
            pieceEntity.setLands(piece.getRatio() != null ? piece.getRatio().getTld() : null);
            collectPieceMapper.insert(pieceEntity);

            //仓名纪录，标记着哪个仓对应的是什么材料
            SiloModel silo = piece.getSilo();
            //配比
            RatioModel ratio = piece.getRatio();
            //将盘次数据中的计量值和仓名对应上
            if (silo != null) {
                //计量值编号
                String[] codeArr = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j"};
                Map<String, Object> siloMap = Convert.toMap(String.class, Object.class, silo);
                Map<String, Object> pieceMap = Convert.toMap(String.class, Object.class, piece);
                Map<String, Object> ratioMap = Convert.toMap(String.class, Object.class, ratio);
                //对有效仓数进行遍历
                for (int i = 0; i < Integer.parseInt(piece.getLc()); i++) {
                    //计量值
                    Double j = (Double) (pieceMap.get("j" + codeArr[i]));
                    if (!"0.0".equals(j.toString())) {
                        CollectDosageEntity dosageEntity = new CollectDosageEntity();
                        dosageEntity.setParentPkId(pieceEntity.getPkId());
                        //料仓名
                        dosageEntity.setStorage((String) (siloMap.get("n" + i)));
                        //原料名
                        dosageEntity.setMaterial((String) (siloMap.get("w" + i)));
                        //原材料规格
                        dosageEntity.setSpec((String) (siloMap.get("t" + i)));
                        //含水率
                        dosageEntity.setWatFull((Double) (siloMap.get("m" + i)));
                        //如果配比不为空，从配比中获取配方值
                        if (ratio != null) {
                            //配方值
                            dosageEntity.setRecAmnt(new BigDecimal(ratioMap.get("dz" + i).toString()).setScale(2, RoundingMode.HALF_UP).stripTrailingZeros().doubleValue());
                        }
                        //设定值
                        dosageEntity.setPlanAmnt(new BigDecimal(pieceMap.get("t" + codeArr[i]).toString()).setScale(2, RoundingMode.HALF_UP).stripTrailingZeros().doubleValue());
                        //实际用量
                        dosageEntity.setFactAmnt(new BigDecimal(j.toString()).setScale(2, RoundingMode.HALF_UP).stripTrailingZeros().doubleValue());
                        collectDosageMapper.insert(dosageEntity);
                    }
                }
            }
        }
        try{
            productPkIdSend(productEntity.getPkId());
        } catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 生产数据统计
     *
     * @param params 查询条件
     */
    @Override
    public IPage<StatisticsProductDto> statisticsProduct(Map<String, Object> params) {
        IPage<StatisticsProductDto> page = baseServiceComponent.getPage(params, StatisticsProductDto.class);
        return baseMapper.statisticsProduct(page, params);
    }

    @Override
    public List<CollectProductDto> getDataList(Map<String, Object> params) {
        return baseMapper.getDataList(params);
    }

    /**
     * 数据主键同步(用以处理雪花算法造成的主键位数过大问题，仅处理博硕厂家)
     */
    @Override
    public void dataPrimaryKeySynchronization() {
        //取出待同步的所有拌合站数据
//        List<CollectProductDto> list = baseMapper.getCopyDataList();
//        for (CollectProductDto dto: list) {
//            List<CollectPieceDto> pieceList = baseMapper.getCopyPieceDataList(dto.getPkId());
//            //遍历添加详情数据
//            for (CollectPieceDto pieceDto:pieceList) {
//                List<CollectDosageDto> dosageList = baseMapper.getCopyDosageDataList(pieceDto.getPkId());
//                pieceDto.setDosageList(dosageList);
//                pieceDto.setPkId(null);
//            }
//            dto.setPieceList(pieceList);
//            //去除pkid
//            dto.setPkId(null);
//            System.out.println(dto);
//            saveCollectData(dto);
//            System.out.println("完成数据同步");
//        }

    }

    private void productPkIdSend(Long pkid) throws IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet("http://111.14.222.59:9163/prod-api/zhgd/dosage/test/"+pkid);
        CloseableHttpResponse response = httpClient.execute(httpGet);
        int status = response.getStatusLine().getStatusCode();
        if (status >= 200 && status < 300) {
            // 对得到后的实例可以进行处理，例如读取回复体，读取html
            HttpEntity entity = response.getEntity();
            System.out.println(new Date());
            System.out.println("=======================");
            String html = EntityUtils.toString(entity);
            System.out.println(html);
        } else {
            throw new ClientProtocolException("Unexpected response status: " + status);
        }
        // 6. 释放连接
        response.close();
        httpClient.close();
    }

}
